<template>
  <el-container>
    <el-aside width="500px">
      <el-col>
        <el-table
            :data="this.myCart"
            style="width: 100%;text-align: center">
          <el-table-column
              prop="name"
              label="名称"
              width="100">
          </el-table-column>
          <el-table-column
              prop="price"
              label="价格"
              width="100">
          </el-table-column>
          <el-table-column
              prop="buyNum"
              label="数量"
              width="50">
          </el-table-column>
          <el-table-column>
            <template slot-scope="scope">
              <el-button @click="deleteFromCart(scope.row)" type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div>
        <el-table
            ref="singleTable"
            highlight-current-row
            @current-change="handleCurrentChange"
            :data="this.myAddress"
            style="width: 100%;text-align: center">
          <el-table-column
              prop="province"
              label="省"
              width="80">
          </el-table-column>
          <el-table-column
              prop="city"
              label="城市"
              width="80">
          </el-table-column>
          <el-table-column
              prop="area"
              label="地区"
              width="70">
          </el-table-column>
          <el-table-column
              prop="address"
              label="地址"
              width="150">
          </el-table-column>
          <el-table-column
              prop="telephone"
              label="电话"
              width="100">
          </el-table-column>
          <el-table-column>
            <template slot-scope="scope">
              <el-button @click="deleteFromCart(scope.row)" type="text" size="small">删除</el-button>
            </template>
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="deleteData(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        </div>
        <div>
          <el-button @click="deleteAllCart()" type="danger" size="small">删除全部</el-button>
          <el-button @click="submitCart()" type="primary" size="small">提交购买</el-button>
          <label size="medium">   总金额{{this.price}}</label>
        </div>

      </el-col>
    </el-aside>
    <el-main>
      <el-row :style="{'min-height': ($window.height-116)+'px',clear:'right'}">
      <el-col :span="8" v-for="map in mymapList" :key="map.id" style="width:20%;height: 70%;margin: 2%">
        <el-popover placement="top" title="简介" width="236" trigger="hover" :content="map.description">
          <el-card :body-style="{ padding: '0px' }" slot="reference">
            <img :src="map.photo"
                 :style="{position:'relative',left:'15px',top:'5px',width:'90%',height:'200px'}"
                 class="image">
            <div style="padding-left: 15px;padding-bottom: 25px">
              <div><span>{{map.name}}</span></div>

              <div style="float:left">
                <el-tag size="mini">价格：{{map.price}} </el-tag>
              </div>
<!--              <div style="float:left">-->
<!--                <el-tag size="mini">  商品类别：{{map.categoryId}}</el-tag>-->
<!--              </div>-->
              <el-input-number v-model="map.buyNum" @change="handleChange" :min="1" :max="10" label="购买数量" size="small"></el-input-number>
              <el-button type="primary" class="button" style="float:right" @click="addToCart(map)">购买 </el-button>
            </div>
          </el-card>
        </el-popover>
      </el-col>
    </el-row>
    <div style="height: 12px"></div>
    <div style="height:12%;width: 100%;text-align:center;">
      <el-pagination v-model="pagemodel"
                     :page-size="pageSize"
                     layout="prev, pager, next"
                     :total="mytotal"
                     background
                     @current-change="ChangePage">
      </el-pagination>
    </div>
    <div style="height: 12px"></div>
    </el-main>
  </el-container>
</template>

<script>

import addaddress from "../components/updateDialog/addaddress";
import qs from "qs";

export default {
  name: "mapMarket",
  mounted() {
    let token = sessionStorage.getItem('token')
    this.token = token
    console.log(token)
    let url = this.$URL.userinfo+"?token="+token.replace("\"","")
    let url2 = url.substring(0,url.length -1)
    //console.log("get"+url2)
    let tempId=''
    this.$axios.get(url2).then(res=>
        {
          this.userId=res.data.id
          tempId = res.data.id
          console.log("zhehsi"+this.userId)

          this.$axios.get(this.$URL.findaddressBycusId+"?id="+this.userId).then(res=> {
            this.myAddress = res.data
            console.log(res)
          }).catch(err=>{})
          //如果当前是登录状态，则显示用户/管理员中心
        }).catch(err=>{})

    this.$axios.post(this.$URL.queryproduct+"?page="+(this.pageNo-1)+"&pageSize="+this.pageSize).then(res=>{
      this.mytotal=res.data.total;
      // this.mymapList=res.data.list;
      for (let temp in res.data.list){
        console.log(res.data.list[temp])
        let x = res.data.list[temp]
        x['buyNum']=0
        if (!x.photo){
          x.photo="https://qcloud.dpfile.com/pc/gDPfocffs6aQyAXw4unZTgczPcoTily48NuZ173LhgTtXniwAabGxFE0zBtKu9f25g_3Oo7Z9EXqcoVvW9arsw.jpg"
          this.mymapList.push(x)
        }
        else {
          this.mymapList.push(x)
        }
        if(!x.name){
          x.name="暂无名称"
        }
        if(!x.price){
          x.price="暂无"
        }
      }
      console.log(this.mymapList)
    }).catch(err=>{})
  },
  data(){
    return{
      mymapList:[],
      myAddress:[],
      price:0,
      myCart:[],
      customerId:28,
      chosenAddress:0,
      userId:0,
      token:'',
      pagemodel:'',
      mytotal:0,
      pageNo:1,
      pageSize:8,
      num:1,
      buyNum:0,
      components:{
        addaddress
      },
      currentRow:null
    }
  },
  methods:{
    switchUrl(url)
    {
      window.open(url);
    },
    chooseAddress(row){
      let dataId = row.data.id
      this.chosenAddress=dataId
    },
    addToCart(map)
    {
      let a = []
      a['id'] = a.length
      a['name'] = map.name
      a['price'] = map.price
      a['number'] = map.buyNum
      a['productId'] = map.id
      this.price+=map.price*map.buyNum
      this.myCart.push(a)
      console.log(this.myCart)
    },
    deleteFromCart(row){
      this.myCart.splice(row.id,1)
    },
    deleteAllCart(){
      this.myCart=[]
    },
    submitCart(){
      let that = this
      let orderLines = that.myCart

      let cartParams = qs.stringify({
        orderLines: this.myCart,
        customerId: this.customerId,
        addressId: this.chosenAddress,
      }, {indices: false});
      that.$axios.post(that.$URL.saveorder, cartParams).then(
          res => {
            if (res.status == 500) {
              that.$message({
                message: "提交成功",
                type: 'success',
              });
              //that.$refs.ruleForm.resetFields();
            } else {
              that.$message({
                message: "提交失败",
                type: 'error'
              });
            }
          }
      );
    },
    ChangePage(currentPage)
    {
      this.pageNo=currentPage;
      this.$axios.post(this.$URL.queryproduct+"?page="+(this.pageNo-1)+"&pageSize="+this.pageSize).then(res=>{
        this.mytotal=res.data.total;
        let result = []
        for (let temp in res.data.list){
          console.log(res.data.list[temp])
          let x = res.data.list[temp]
          x['buyNum']=this.mymapList.buyNum
          if (!x.photo){
            x.photo="https://qcloud.dpfile.com/pc/gDPfocffs6aQyAXw4unZTgczPcoTily48NuZ173LhgTtXniwAabGxFE0zBtKu9f25g_3Oo7Z9EXqcoVvW9arsw.jpg"
            result.push(x)
          }
          else {
            result.push(x)
          }
          if(!x.name){
            x.name="暂无名称"
          }
          if(!x.price){
            x.price="暂无"
          }
        }
        this.mymapList=result;
      }).catch(err=>{})
    },
    handleChange(value) {
      this.buyNum = value
      console.log(this.buyNum);
    },
    deleteData(row){
      let that=this
      // let needURL=deleteDataURLlist[that.typevalue]+dataId
      let dataId = row.id
      console.log(row.id)
      let needURL=that.$URL.deleteaddress+'?id='+dataId
      console.log(needURL)
      that.$axios.get(needURL,"").then(
          res => {
            if (res.status == 500){
              that.$message({
                message: "删除商品不存在",
                type: 'warning'
              });
            }
            else if(res.status == 200){
              that.$message({
                message: "删除成功",
                type: 'success'
              })
              that.tableData.length=0
            }
          }
      )
    },

    updateAdd(row){
      this.$Bus.$emit('addaddress',{
        infoData:row,
        dialogVisible:true
      })
    },

    setCurrent(row) {
      this.$refs.singleTable.setCurrentRow(row);
    },
    handleCurrentChange(val) {
      this.currentRow = val;
      console.log(val)
      this.chosenAddress = val.id
      console.log(this.chosenAddress)
    }
  }
}
</script>

<style scoped>
.button {
  margin: 2px;
  padding: 5px;
  float: right;
}
.image {
  width: 100%;
}
.el-table-column{
  text-align: center;
}

</style>